package com.windrift.springhibernate.service;

import com.windrift.springhibernate.model.Cost;
import com.windrift.springhibernate.service.CostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional
@Service("costService")
public class CostServiceImpl implements CostService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<Cost> findAll() {
        Query query = getEntityManager().createQuery("SELECT a FROM Cost a ORDER BY costDate ASC");
        return query.getResultList();
    }

    private void save(Cost cost) {
        if (cost.getId() == null) {
            // new
            em.persist(cost);
        } else {
            // update
            em.merge(cost);
        }
    }

    public void remove(int id) {
        Cost cost = find(id);
        if (cost != null) {
            em.remove(cost);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public Cost find(int id) {
        return em.find(Cost.class, id);
    }

    public void add(Cost cost) {
        this.save(cost);
    }

    public void update(Cost cost) {
        this.save(cost);
    }

}
